#!/usr/bin/env node

var inquirer = require('inquirer');
var shell = require("shelljs");

if (!shell.which('git')) {
	shell.echo('Sorry, this script requires git');
	shell.exit(1);
	return;
}
var branchType = {
	type: 'list',
	name: 'branchType',
	message: '哪种任务：',
	choices: [
		{
			name: 'bug',
			value: 'hotfixes'
		},
		{
			name: '需求',
			value: 'feature'
		}
	]
};

var bugTaskName = {
	type: 'input',
	name: 'taskName',
	message: '输入bugId和名称：',
	validate: function (input) {
		if (!input) {
			return '不能为空';
		}
		return true;
	}
};

var featureTaskName = {
	type: 'input',
	name: 'taskName',
	message: '输入需求名称：',
	validate: function (input) {
		if (!input) {
			return '不能为空';
		}
		return true;
	}
};

function bugTask(branchType) {
	inquirer
		.prompt([bugTaskName])
		.then(answers => answers.taskName)
		.then(taskName => {
			gitCreateBranch(branchType, taskName);
		});
}

function featureTask(branchType) {
	inquirer
		.prompt([featureTaskName])
		.then(answers => answers.taskName)
		.then(taskName => {
			gitCreateBranch(branchType, taskName);
		});
}

function gitCreateBranch(branchType, taskName) {
	var exec = require('child_process').exec;
	// 打印当前分支名
	exec('git symbolic-ref --short -q HEAD', function (stderr, stdout) {
		console.log(`-----⚡️ 签出分支：${stdout}`);
		exec(`git checkout -b ${branchType}-${taskName}`, function (err, stdout, stderr) {
			if (err) {
				console.log('-----stderr-----');
				console.log(stderr);
				return;
			}
			console.log('-----😁 创建成功-----');
			console.log(`-----🥤 【${branchType}-${taskName}】------`);
		});
	});
}

inquirer.prompt([branchType])
	.then(answers => answers.branchType)
	.then(branchType => {
		if (branchType === 'hotfixes') {
			bugTask(branchType);
		} else {
			featureTask(branchType);
		}
	});
